<template>
  <div class="app-container" style="padding:20px">
    <el-card>
      <template #header>
        <AmFormHeader title="档案著录" @submit="submitForm" @cancel="closeThisPage" />
      </template>
      <el-form :model="form" :rules="rules" ref='form' label-width="120px">
        <el-divider content-position="left">档案基本信息</el-divider>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="档案编号" prop="descriptionNo">
              <el-input v-model="form.descriptionNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="案卷号" prop="fileCode">
              <el-input v-model="form.fileCode" placeholder="请输入案卷号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="档案类别" prop="folderId">
              <AmFolderTreeSelector v-model="form.folderId"
                                    @select="handleFolderChange" />
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="档案级别" prop="groupId">
              <AmGroupSelector v-model="form.groupId" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="归档时间" prop="archiveTime">
              <el-date-picker clearable
                              v-model="form.archiveTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择归档时间"
                              class="am-w-full"/>
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="历史时期" prop="historicalPeriod">
              <AmDictSelector v-model="form.historicalPeriod" dict="description_historical_period" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="载体类型" prop="carrierType">
              <AmDictSelector v-model="form.carrierType" dict="carrier_type" />
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="文种" prop="recordType">
              <AmDictSelector v-model="form.recordType" dict="description_record_type" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="数量" prop="number">
              <el-input v-model="form.number" placeholder="请输入数量"/>
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="单位" prop="unit">
              <AmDictSelector v-model="form.unit" dict="description_unit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="规格" prop="spec">
              <AmDictSelector v-model="form.spec" dict="description_spec" />
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="页数" prop="paginalNum">
              <el-input v-model="form.paginalNum" placeholder="请输入页数"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.full">
            <el-form-item label="主题词" prop="keyword">
              <el-input v-model="form.keyword" placeholder="请输入主题词"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.full">
            <el-form-item label="提名" prop="title">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入提名"
                        v-model="form.title"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.full">
            <el-form-item label="备注" prop="notes">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入备注"
                        v-model="form.notes"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">馆藏信息</el-divider>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="档案柜" prop="cabinetId">
              <AmCabinetTreeSelector v-model="form.cabinetId" />
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="全宗" prop="keyword">
              <el-input v-model="form.fondCode" placeholder="请输入全宗"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="保存期限" prop="saveDate">
              <AmDictSelector v-model="form.saveDate" dict="description_save_date" />
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="发文字号" prop="dispatchNumber">
              <el-input v-model="form.dispatchNumber" placeholder="请输入发文字号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="立卷时间" prop="filingTime">
              <el-date-picker clearable
                              v-model="form.filingTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择案卷立案时间"
                              class="am-w-full"/>
            </el-form-item>
          </el-col>
          <el-col v-bind="formColumnConfig.half">
            <el-form-item label="立卷人" prop="filingPerson">
              <el-input v-model="form.filingPerson" placeholder="请输入立卷人"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">案卷立案时间范围</el-divider>
        <el-row>
          <el-col v-bind="formColumnConfig.full">
            <el-form-item label="案卷立案周期" prop="startTime">
              <el-date-picker
                  v-model="formTemp.timeRange"
                  type="daterange"
                  align="right"
                  unlink-panels
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="am-w-full"
                  @change="handleRangeChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">扩展索引</el-divider>
        <el-row>
          <el-col v-bind="formColumnConfig.full">
            <el-form-item label="扩展索引" prop="extendedIndex">
              <el-tag class="extend-index-tag"
                  :key="tag"
                  v-for="tag in extendedIndex"
                  closable
                  :disable-transitions="false"
                  @close="handleRemoveIndex(tag)">
                {{tag}}
              </el-tag>
              <el-input
                  class="input-new-tag"
                  v-if="extendedIndexInputVisible"
                  v-model="extendedIndexInputValue"
                  ref="indexInputRef"
                  size="small"
                  @keyup.enter.native="handleIndexConfirm"
                  @blur="handleIndexConfirm"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small"
                         @click="showIndexInput">+ 新增索引</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">附件列表</el-divider>
        <am-directory-uploader ref="AmDirectoryUploaderRef" />
<!--        <el-row>-->
<!--          <el-col v-for="type in formTemp.fileTypes" :key="type.dictValue">-->
<!--            <h5>{{ type.dictLabel }}</h5>-->
<!--            <AmFilesUploader v-model="formTemp.fileTypesMap[type.dictValue]" />-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {addDescription, getDescription, updateDescription} from "../../../api/am/description";
import {Message} from "element-ui";
import AmFilesUploader from "../../../components/AmComp/AmFilesUploader.vue";
import AmFormHeader from "../../../components/AmComp/AmFormHeader.vue";
import {isEmpty, isNull, isUndefined} from "lodash";
import AmDictSelector from "../../../components/AmComp/AmDictSelector.vue";
import AmGroupSelector from "../amGroup/AmGroupSelector.vue";
import AmFolderTreeSelector from "../amFolder/AmFolderTreeSelector.vue";
import {copyByKey, isValueExist} from "../../../utils/tools";
import AmCabinetTreeSelector from "../amCabinet/AmCabinetTreeSelector.vue";
import AmDirectoryUploader from "./AmDirectoryUploader.vue";

export default {
  components: {
    AmDirectoryUploader,
    AmCabinetTreeSelector,
    AmFolderTreeSelector,
    AmGroupSelector,
    AmDictSelector,
    AmFormHeader,
    AmFilesUploader
  },
  data() {
    return {
      // 档案分类
      groupList:[],
      // 扩展索引
      extendedIndex: [],
      extendedIndexInputValue: '',
      extendedIndexInputVisible: false,
      // 表单
      formTemp: {
        timeRange: [],
        groupIds: [],
        selectedFolder: null,
        fileTypes: [],
        fileTypesMap: {},
      },
      form: {
        // 主键
        id: '',
        // 案卷号
        fileCode: '',
        // 档案类别
        folderId: '',
        // 归档时间
        archiveTime: '',
        // 档案级别
        groupId: '',
        // 提名
        title: '',
        // 主题词
        keyword: '',
        // 备注
        notes: '',
        // 档案柜
        cabinetId: '',
        // 全宗
        fondCode: '',
        // 保存期限
        saveDate: '',
        // 发文字号
        dispatchNumber: '',
        // 立卷时间
        filingTime: '',
        // 立卷人
        filingPerson: '',
        // 案卷立案开始时间
        startTime: '',
        // 案卷立案结束时间
        endTime: '',
        // 扩展索引
        extendedIndex: '',
        // 文件
        fileVOS: [],
        // 历史时期
        historicalPeriod: '',
        // 数量
        number: '',
        // 单位
        unit: '',
        // 页数
        paginalNum: '',
        // 载体类型
        carrierType: '',
        // 规格
        spec: '',
        // 文种
        recordType: '',
        // 档案编号
        descriptionNo: '',
      },
      rules: {
        fileCode: [
          { required: true, message: "案卷号不能为空", trigger: "blur" }
        ],
        folderId: [
          { required: true, message: "档案类别不能为空", trigger: "blur" }
        ],
        archiveTime: [
          { required: true, message: "归档时间不能为空", trigger: "blur" }
        ],
        groupId: [
          { required: true, message: "档案级别不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "提名不能为空", trigger: "blur" }
        ],
        cabinetId: [
          { required: true, message: "档案柜不能为空", trigger: "blur" }
        ],
      },
      cabinetTree: [],
      readonly: false,
      formColumnConfig: {
        half: {
          xs: 24,
          sm: 12,
          md: 8,
          lg: 8,
        },
        full: {
          xs: 24,
          sm: 12,
          md: 16,
          lg: 16,
        },
      },
    }
  },
  watch: {
    'form.fileCode': {
      handler() {
        this.noGenerator()
      },
      deep: true
    },
    'form.fondCode': {
      handler() {
        this.noGenerator()
      },
      deep: true
    },
  },
  async created() {
    // this.form.id = this.$route.params && this.$route.params.formId;
    // // await this.loadFileType();
    // if (this.form.id) {
    //   this.recoveryForm();
    // }
  },
  mounted() {
    this.form.id = this.$route.params && this.$route.params.formId;
    // await this.loadFileType();
    // if (this.form.id) {
    //   this.recoveryForm();
    // }
    this.recoveryForm();
  },
  methods: {
    async loadFileType() {
      const { data } = await this.getDicts('description_file_type')
      this.formTemp.fileTypes = data
      this.formTemp.fileTypesMap = {}
      data.forEach(item => {
        this.formTemp.fileTypesMap[item.dictValue] = []
      })
    },
    handleFolderChange(folder) {
      this.formTemp.selectedFolder = folder
      this.noGenerator()
    },
    noGenerator() {
      const { fondCode, fileCode } = this.form
      const code = isNull(this.formTemp.selectedFolder) ? '' : this.formTemp.selectedFolder.code
      this.$set(this.form, 'descriptionNo', `${fondCode}${code}${fileCode}`)
    },
    handleRemoveIndex(index) {
      this.extendedIndex = this.extendedIndex.filter(item => item !== index);
    },
    handleIndexConfirm() {
      const inputValue = this.extendedIndexInputValue
      if (inputValue) {
        if(this.extendedIndex.includes(inputValue)) {
          Message.warning('索引已存在，请勿重复添加');
        } else {
          this.extendedIndex.push(inputValue);
        }
      }
      this.extendedIndexInputVisible = false;
      this.extendedIndexInputValue = '';
    },
    showIndexInput() {
      this.extendedIndexInputVisible = true;
      this.$nextTick(() => {
        this.$refs.indexInputRef.focus();
      })
    },
    handleRangeChange() {
      this.form.startTime = this.formTemp.timeRange[0];
      this.form.endTime = this.formTemp.timeRange[1];
    },
    /** 回填表单数据 */
    recoveryForm() {
      if (this.form.id) {
        getDescription(this.form.id).then(response => {
          copyByKey(this.form, response.data)
          if(!isEmpty(this.form.extendedIndex)) {
            this.extendedIndex = this.form.extendedIndex.split(',')
          }
          if(!isEmpty(this.form.startTime) && !isEmpty(this.form.endTime)) {
            this.formTemp.timeRange = [this.form.startTime, this.form.endTime]
          }
          this.$refs.AmDirectoryUploaderRef.recoveryFiles(this.form.fileVOS)
          // if(!isEmpty(this.form.fileVOS)) {
          //   this.form.fileVOS.forEach(file => {
          //     if(isUndefined(this.formTemp.fileTypesMap[file.fileType])) {
          //       this.formTemp.fileTypesMap[file.fileType] = [file]
          //     } else {
          //       this.formTemp.fileTypesMap[file.fileType].push(file)
          //     }
          //   })
          // }
        })
      } else {
        this.$refs.AmDirectoryUploaderRef.recoveryFiles()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if(!isEmpty(this.extendedIndex)) {
            this.form.extendedIndex = this.extendedIndex.join(',');
          }
          this.form.fileVOS = this.$refs.AmDirectoryUploaderRef.getFiles();
          // Object.keys(this.formTemp.fileTypesMap).forEach(key => {
          //   if(!isEmpty(this.formTemp.fileTypesMap[key])) {
          //     this.form.fileVOS.push(...this.formTemp.fileTypesMap[key].map(file => ({
          //       ...file,
          //       fileType: key,
          //     })))
          //   }
          // })
          if (isValueExist(this.form.id)) {
            updateDescription(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.closeThisPage();
            });
          } else {
            addDescription(this.form).then(response => {
              this.$modal.msgSuccess('保存成功');
              this.closeThisPage();
            });
          }
        }
      })
    },
    closeThisPage() {
      this.$tab.closeOpenPage({path: '/am/amDescription'});
    },
  }
}
</script>

<style lang="scss" scoped>
.extend-index-tag{
  height: 32px;
  line-height: 32px;
  & + .extend-index-tag{
    margin-left: 8px;
  }
}
.button-new-tag {
  margin-left: 8px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 8px;
  vertical-align: bottom;
}
</style>
